<template>
    <div id="createTest" class="container">
      <div class="wrapper">
        <div class="left">
          <div class="header">
            {{testInfo?.name}} 
          </div>
          <div v-for="kv,index in catedQuestions" :key="kv[0]">
            <div class="cate" v-show="kv[1].length !== 0">
              {{ kv[0] }} 
            </div>
            <div 
              class="quest" 
              @click="enter(question)" 
              v-for="(question,index) in kv[1]" 
              :key="question._id"
              :style="{backgroundColor:culBackcolor(question._id)}"
            >
              {{ index + 1 }}
              <span v-show="done.has(question._id)" style="float: right;">
                <el-icon v-if="paper?.answers.find(a => a.questionId === question._id)?.getPoint !== 0"><Check /></el-icon>
                <el-icon v-else><Close /></el-icon>
              </span>
            </div>
          </div>
        </div>
        <div class="right">
            <div class="controllers">
                <div style="color:#a6a6a6">总分： {{ score }}</div>
                <ElButton @click="save" type="primary" style="margin-right: 10px;">提交</ElButton>
            </div>
            <div class="form">
                <div v-if="currentAnswer">
                    <div class="item">
                        <div class="hint">题目:</div>
                        {{ currentQues?.question.question }}
                    </div>
                    <div class="item" v-if="currentAnswer?.answer !== undefined">
                        <div class="input" >
                            <span class="hint">学生答案:</span>
                            <ElInput v-model="currentAnswer!.answer" :disabled="true"></ElInput>
                        </div>
                    </div>
                    <div class="item" v-if="currentAnswer?.answers !== undefined">
                        <span class="hint">
                            学生答案:
                        </span>
                        <div class="input" v-for="(an,index) in  currentAnswer?.answers" :key="index">
                            <ElInput v-model="currentAnswer!.answers[index]" :disabled="true"></ElInput>
                        </div>
                    </div>
                    <div class="item" v-if="currentQues?.question.selections">
                        <div class="hint">正确答案:</div>
                        <el-checkbox :checked="Boolean(currentQues.answer.selections?.find(s => s === sel))" :disabled="true" :key="sel" v-for="sel in currentQues?.question.selections" :label="sel" name="type" />
                    </div>
                    <div class="item" v-if="currentAnswer?.selections !== undefined">
                        <div class="hint">
                            学生答案:
                        </div>
                        <el-checkbox :checked="Boolean(currentAnswer?.selections?.find(s => s === sel))" :disabled="true" :key="sel" v-for="sel in currentQues?.question.selections" :label="sel" name="type" />
                    </div>
                    <div class="item">
                        <div class="hint">得分: <span style="margin-left: 10px;">(满分:{{ currentQues?.question.score }})</span></div>
                        <ElInputNumber v-model="currentAnswer!.getPoint" :min="0" :max="currentQues?.question.score"></ElInputNumber>
                    </div>

                    <div class="foot">
                        <ElButton style="float: left;" plain type="primary" @click="currentAnswer!.getPoint = currentQues!.question.score">回答正确</ElButton>
                        <ElButton style="float: left;" plain type="danger" @click="currentAnswer!.getPoint = 0">回答错误</ElButton>
                        <ElButton @click="nextQues">下一题</ElButton>
                    </div>
                </div>
                <div v-else>
                  <div style="height: 200px;line-height: 200px;">点击题目查看详情</div>
              </div>
            </div>
        </div>
      </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted,reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { useClientStore } from "../../pinia/stores/client";
import { studentAnswer } from "@/shared/types/Answer";
import { questions } from "@/shared/types/Question";

const route = useRoute();
const router = useRouter();
const examOrHomework = ref<'exam' | 'homework'>((route.name as 'judgePaper' | 'judgeHomework') === 'judgePaper'?'exam':'homework')
const testId = route.params.testId as string;
const student = route.query.student as string;
const { currentCourseId,client } = storeToRefs(useClientStore());

let loadingInstance:any

const paper = ref<{
    _id: string
    student: string
    test: string
    submitTime: Date
    answers: Array<studentAnswer>
    score:number
    studentInfo: {
        _id: string;
        name: string;
        password?: string;
        role: string;
        email: string;
        school: string;
        number: string;
        gender: number;
        portrait: string;
    }[];
}>()
const testInfo = ref<{
    _id: string,
    course: string,
    startTime: Date,
    endTime: Date,
    name: string,
    status: "saved" | "published"
    questions:Array<questions>
}>()
const catedQuestions = computed(() =>{
  const qus = new Map<string,Array<questions>>()
  qus.set('选择题',new Array<questions>())
  qus.set('填空题',new Array<questions>())
  qus.set('简答题',new Array<questions>())
  qus.set('判断题',new Array<questions>())
    testInfo.value?.questions.forEach(question =>{
    qus.get(question.question.type)?.push(question)
  })

  return qus
})
const score = computed(() =>{
    if(!paper.value) return 0
    const s = paper.value.answers.reduce((per,cur,arr)=>{
        return per + cur.getPoint
    },0)
    if(paper.value) paper.value.score = s as number
    return s
})

const culBackcolor = (id:string)=>{
  if( currentQues.value?._id === id){
    return '#fde2e247'
  }
}

const currentQues = ref<questions>()
const currentAnswer = ref<studentAnswer>()
const done = ref(new Set<string>())
const autoJudge = () =>{
    const answer = paper.value?.answers
    if(!answer) return
    let isDone = false
    testInfo.value?.questions.forEach((question,index,arr) =>{
        if(question.question.type === '选择题' || question.question.type === '判断题'){
            // console.log(question.answer.selections?.toString() === answer[index].selections?.toString());
            if(question.answer.selections?.toString() === answer[index].selections?.toString()){
                answer[index].getPoint = question.question.score
            }
            done.value.add(question._id)
        }
        else{
          if(answer[index].getPoint !== 0){
            isDone = true
          }
        }

        if(isDone){
          done.value = new Set(testInfo.value?.questions.map(q => q._id))
        }
       
    })
}
const enter = (question:questions)=>{
  currentQues.value = question
  currentAnswer.value = paper.value?.answers.find(a => a.questionId === question._id)
  
  if(!done.value.has(question._id)) done.value.add(question._id)
//   console.log(question);
}
const nextQues = () =>{
    const cateArrs = [...catedQuestions.value.values()]
    const qus = new Array<questions>()
    cateArrs.forEach(arr =>{
        qus.push(...arr)
    })
    const index = qus.findIndex(q => q._id === currentQues.value?._id)
    
    if(index +1 === qus.length) {
        return ElMessage.warning('已经是最后一题了')
    }
    else{
        enter(qus[index +1])
    }
}
const save = async () =>{
    // console.log(done.value.size,paper.value?.answers.length);
    loadingInstance = ElLoading.service({
          target:'#createTest',
    })
    if(!paper.value) return
    try {
        if(done.value.size === paper.value?.answers.length){

        }
        else{
            await ElMessageBox.confirm('还有没查看的问题，确定提交吗？')
        }
        const ret = await client.value.callApi('QuestionsSys/JudgeTest',{
            examOrHomework:examOrHomework.value,
            score:score.value,
            useTest:paper.value._id,
            answers:paper.value.answers
        })
        if(ret.isSucc){
             ElMessage.success('提交成功')
             router.back()
        }
        loadingInstance.close()

    } catch (error) {
        console.log(error);
    }
}

onMounted(async () => {
  loadingInstance = ElLoading.service({
        target:'#createTest',
  })
  if (!testId || !student) {
    loadingInstance.close()
    ElMessage.error("参数错误");
    router.back();
    return
  }

  const ret = await client.value.callApi('Get/GetTestQuestions',{
        test:testId,
        examOrHomework:examOrHomework.value
    })
    if(ret.isSucc){
        testInfo.value = ret.res.test[0]
        currentCourseId.value = testInfo.value.course
    }

  const ret2 = await client.value.callApi('Get/GetUserTest',{
        testId,
        examOrHomework:examOrHomework.value
        // courseId:currentCourseId.value
    })
    if(ret2.isSucc){
        const papers = ret2.res.tests
        if(papers.length === 0) {
            ElMessage.error('不存在')
            router.back()
            return
        }
        paper.value = papers.find(p => p.student === student)

        autoJudge()
    }

    loadingInstance.close()
});
</script>


<style lang="less" scoped>
@fontColor: #a6a6a6;
*{
  user-select: none;
}
.container {
  height: 100%;
  width: 100%;
  background-color: #f2f4f7;
  padding: 5vh 0;
  overflow: auto;
  .wrapper {
    width: 80%;
    height: 90%;
    // background-color: aliceblue;
    position: relative;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;

    .left {
      width: 25%;
      height: 100%;
      background-color: white;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding-top: 50px;
      &>div>div{
        .de-btn{
          float: right;
          font-size: 16px;
          display:none;
          line-height: 30px;
          color:#a6a6a6;
        }
      }
      &>div>div:hover{
        background-color: aliceblue;
        .de-btn{
          display: inline;
        }
      }
      .header{
        border-radius: 10px;
        height: 50px;
        color: #000;
        font-size: 20px;
        text-align: left;
        line-height: 65px;
        padding: 0 20px;
        user-select: none;
        position: absolute;
        top: 0;
        left: 0;
        background: white;
      }
      .cate{
        height: 30px;
        color: black;
        font-size: 12px;
        font-weight: bold;
        line-height: 30px;
        padding: 0 20px;
        background: white!important;
        // cursor: pointer;
      }
      .quest{
        height: 30px;
        color:@fontColor;
        font-size: 13px;
        line-height: 30px;
        padding: 0 20px;
        cursor: pointer;
      }
    }
    .right {
      width: 72%;
      height: 100%;
      // background-color: white;
      & > div {
        border-radius: 10px;
      }
      .controllers {
        height: 12%;
        width: 100%;
        background-color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 30px;
        .text {
          color: @fontColor;
        }
        .el-button {
          margin-left: 20px;
        }
      }
      .form {
        position: relative;
        margin-top: 4%;
        // height: 80%;
        width: 100%;
        background-color: white;
        text-align: center;
        // line-height: 500px;
        color: @fontColor;
        padding: 40px;
        .hint{
            color: @fontColor;
            font-size: 14px;
        }
        .item{
          // height: 40px;
          text-align: left;
          color: black;
          line-height: 40px;
        //   margin: 10px 0;
          .input{
            // padding: 0 20px;
            padding-left: 0%;
            width: 60%;
            margin-bottom: 10px;
          }
          .selection{
            // padding-left: 20px;
            height: 40px;
          }
        }
        .foot{
          padding-top:10px;
        }
      }
    }
  }
}
</style>
